package com.remoting.api.request.support;

import com.remoting.api.registry.bean.HostInfo;
import com.remoting.api.registry.bean.ServiceImportInfo;
import com.remoting.api.request.RequestHandler;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.Map.Entry;


/**
 * post请求参数
 * <p>说明:</p>
 * <li></li>
 * @author DuanYong
 * @since 2018年12月27日下午1:37:29
 */
public class PostRequest extends RemoteRequest{
	
	public PostRequest(RequestHandler requestHandler, ServiceImportInfo serviceImportInfo, Map<String, Object> params) {
		super(requestHandler,serviceImportInfo,params);
	}
	public PostRequest doBuilder(HostInfo host){
		String address = populatePostAddress(host);
		this.setAddress(address);
		return this;
	}
	/**
	 * 组装POST请求地址
	 * <p>
	 * 说明:
	 * </p>
	 * <li></li>
	 * @param host
	 * @return
	 * @since 2017年3月3日下午1:56:12
	 */
	private String populatePostAddress(HostInfo host) {
		//附加参数
		this.setParams(appendData(this.getServiceImportInfo(),host,this.getParams()));
		//组装URL地址
		StringBuilder address = new StringBuilder();
		address.append(this.getServiceImportInfo().getEndpoint().getType()).append(":").append(host.toUrl())
				.append(this.getServiceImportInfo().getEndpoint().getServiceAddr()).append(this.getServiceImportInfo().getApi());
		if (null == this.getServiceImportInfo().getParams() || this.getServiceImportInfo().getParams().isEmpty()) {
			return address.toString();
		}
		//组装URL请求地址中的参数
		String value = "";
		StringBuilder url = new StringBuilder();
		for (Entry<String,String> entry : this.getServiceImportInfo().getParams().entrySet()) {
			value = entry.getValue();
			if (StringUtils.isBlank(value)) {
				continue;
			}
			value = this.getRequestHandler().parserValue(this.getServiceImportInfo(), host, this.getParams(), value);
			url.append(entry.getKey()).append("=").append(value).append("&");
		}
		if (StringUtils.isNotBlank(url.toString())) {
			address.append("?").append(url.toString().substring(0, url.length() - 1));
		}
		return address.toString();
	}
	
	/**
     * 将附加参数添加到请求参数中
     * <p>说明:</p>
     * <li></li>
     * @param serviceInfo
     * @param host
     * @param data
     * @return
     * @since 2017年3月3日下午5:09:08
     */
	private Map<String,Object> appendData(ServiceImportInfo serviceInfo,HostInfo host, Map<String,Object> data) {
		//将附加参数添加到请求参数中
		if(null == serviceInfo.getDataParams() || serviceInfo.getDataParams().isEmpty()){
			return data;
		}
		String value = "";
		for(Entry<String,String> entry : serviceInfo.getDataParams().entrySet()){
			value = entry.getValue();
			if (StringUtils.isBlank(entry.getValue())) {
				continue;
			}
			value = this.getRequestHandler().parserValue(serviceInfo, host, data, value);
			this.getRequestHandler().parserKey(entry.getKey(),value,data);
			if (!entry.getKey().contains("[")) {
				data.put(entry.getKey(), value);
			}
		}
		return data;
	}
	

}
